package net.itst.schwarzerdaumen;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.IBinder;

public class SDNotifier extends Service {

    private NotificationManager notMgr = null;
    private Notification not = null;
    private Timer timer = null;

    @Override
    public IBinder onBind(Intent arg0) {
	return null;
    }

    @Override
    public void onCreate() {
	super.onCreate();

	notMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
	startService();
    }

    private void startService() {
	timer = new Timer();
	timer.scheduleAtFixedRate(new TimerTask() {
	    @Override
	    public void run() {
		TimeZone tzLocal = TimeZone.getDefault();
		Locale lcLocal = Locale.getDefault();
		Calendar dtNow = new GregorianCalendar(tzLocal, lcLocal);

		String selection = new SimpleDateFormat("dd.MM.yyyy")
			.format(dtNow.getTime());

		SchwarzerDaumenDatabase database = new SchwarzerDaumenDatabase(
			SDNotifier.this.getApplicationContext());
		SQLiteDatabase db = database.getReadableDatabase();

		Cursor curWPlanNow = db.query(TablePlants.TABLE_NAME,
			TablePlants.SQL_GET_STATUS, TablePlants.WNEXT + "=?",
			new String[] { selection }, null, null, null);

		if (curWPlanNow.getCount() > 0) {
		    SDNotifier.this
			    .displayNotificationMessage(R.string.not_need_watering);
		} else {
		    SDNotifier.this.disableNotificationMessage();
		}

		curWPlanNow.close();
		db.close();
	    }
	}, 10000, 5000); // AlarmManager.INTERVAL_HALF_DAY);
    }

    @Override
    public void onDestroy() {
	super.onDestroy();
    }

    @Override
    public void onStart(Intent intent, int startId) {
	super.onStart(intent, startId);
    }

    private void displayNotificationMessage(int resId) {
	not = new Notification(R.drawable.placeholder_plant, this
		.getText(resId), System.currentTimeMillis());
	PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
		new Intent(this, NotificationHandler.class), 0);
	not.setLatestEventInfo(this, this.getText(R.string.app_name), this
		.getText(resId), contentIntent);
	notMgr.notify(R.id.app_notification_id, not);
    }

    private void disableNotificationMessage() {
	notMgr.cancel(R.id.app_notification_id);
    }
}